package com.gzhryc.common.sms;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.lang3.StringUtils;

/**
 * SMS短信服务
 * @author 张浩
 * @version 2016-12-2
 */
public class SmsService {

	static AtomicBoolean isRun = new AtomicBoolean(false);
	
	static BlockingQueue<SmsMessage> Queue = new ArrayBlockingQueue<SmsMessage>(100000);
	
	static ISmsHandler handler;
	static Integer threadNumber;
	
	public static void open(Integer threadNum,ISmsHandler smsHandler){
		threadNumber = threadNum;
		handler = smsHandler;
		isRun.set(true);
		for(int i=0;i<threadNumber;i++){
			new ThreadHandler().start();
		}
	}
	
	public static void close(){
		isRun.set(false);
		for(int i=0;i<threadNumber;i++){
			try {
				Queue.put(new SmsMessage());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		new Thread(){
			public void run(){
				try {
					Thread.sleep(1000);
					Queue.clear();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	public static boolean sendMessage(SmsMessage msg){
		try{
			if(isRun.get()){
				return Queue.add(msg);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean synSendMessage(SmsMessage msg){
		try{
			ISmsHandler handler = SmsService.getHander();
			if(handler != null){
				return SmsService.getHander().send(msg);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 同线程发送手机验证码
	 * @param phone
	 * @return
	 */
	public static boolean synSendPhoneVerifyCode(String phone,String code,String sign){
		ISmsHandler handler = SmsService.getHander();
		if(handler != null){
			SmsPhoneVerifyMessage msg = new SmsPhoneVerifyMessage();
			msg.setSign(sign);
			msg.setPhone(phone);
			msg.setContent(code);
			return SmsService.getHander().send(msg);
		}
		return false;
	}
	
	public static ISmsHandler getHander(){
		return handler;
	}
	
	public static class ThreadHandler extends Thread {
		
		public void run(){
			while(isRun.get()){
				try {
					SmsMessage msg = Queue.take();
					if(StringUtils.isNotBlank(msg.getPhone()) 
							&& StringUtils.isNotBlank(msg.getContent())){
						handler.send(msg);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
